package com.daisuxia.back.controller;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.ExcelUtil;
import com.daisuxia.back.utils.PropertiesUtil;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.pojo.ChannelInfo;
import com.daisuxia.web.pojo.ChannelReport;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IChannelInfoService;
import com.daisuxia.web.service.IChannelReportService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.Base64Utils;
import com.daisuxia.web.util.ConfigConstant;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.QrCodeUtil;
import com.daisuxia.web.util.encrypt.AESUtil;
import com.daisuxia.web.util.encrypt.MD5coding;

@Controller
@RequestMapping("channel/")
public class ChannelInfoController extends BaseController {

	private static Logger logger = LoggerFactory
			.getLogger(ChannelInfoController.class);

	 @Autowired
	 private IChannelInfoService channelInfoService;
	 @Autowired
	 private IChannelReportService channelReportService;
	 @Autowired
	 private IUserService userService;
 

	 /**
		 * 推广渠道分页
		 * @param request
		 * @param response
		 * @param model
		 * @return
		 */
	@RequestMapping("getChannelInfoPage")
	public String getChannelInfoPage(HttpServletRequest request,HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			//params.put("noAdmin", Constant.ADMINISTRATOR_ID);
			PageConfig<ChannelInfo> pageConfig = channelInfoService.findPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/channelInfoPage";
	}
	
	/**
	 * 推广员分页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getChannelUserInfoPage")
	public String getChannelUserInfoPage(HttpServletRequest request,HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			BackUser backUser=this.loginAdminUser(request);
			if(backUser!=null&&!StringUtils.isBlank(backUser.getUserAddress())){
				HashMap<String, Object> pm = new HashMap<String,Object>();;
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo= channelInfoService.findOneChannelInfo(pm);
				if(channelInfo!=null){
					params.put("channelCode", channelInfo.getChannelCode());
				}
			}
			PageConfig<ChannelInfo> pageConfig = channelInfoService.findChannelUserPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
			String bpath = request.getContextPath();
			model.addAttribute("bpath",bpath);

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/channelUserInfoPage";
	}
	
	/**
	 * 推广记录分页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getChannelRecordPage")
	public String getChannelRecordPage(HttpServletRequest request,HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			BackUser backUser=this.loginAdminUser(request);
			if(backUser!=null&&!StringUtils.isBlank(backUser.getUserAddress())){
				HashMap<String, Object> pm = new HashMap<String,Object>();;
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo= channelInfoService.findOneChannelInfo(pm);
				if(channelInfo!=null){
					params.put("channelCode", channelInfo.getChannelCode());
				}
			}
			//params.put("noAdmin", Constant.ADMINISTRATOR_ID);
			PageConfig<ChannelInfo> pageConfig = channelInfoService.findChannelRecordPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/channelRecordPage";
	}
	

	/**
	 * 添加或修改推广渠道
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("saveUpdateChannelInfo")
	public String saveUpdateChannelInfo(HttpServletRequest request,
			HttpServletResponse response, Model model, ChannelInfo channelInfo) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (params.containsKey("id")) {
					// 更新的页面跳转
					channelInfo = channelInfoService.findOneChannelInfo(params);
					model.addAttribute("channelInfo", channelInfo);
				}
				url = "userInfo/editChannelInfo";
			} else {
				channelInfo.setStatus(1);
				// 更新或者添加操作
				if (channelInfo.getId() != null) {
					channelInfoService.updateById(channelInfo);
				} else {
					channelInfoService.insert(channelInfo);
				}
				SpringUtils.renderDwzResult(response, true, "操作成功",
						DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
								.toString());
			}
		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				SpringUtils.renderDwzResult(response, false, "操作失败,原因："
						+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get(
						"parentId").toString());
			}
			logger.error("添加渠道信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}
	
	/**
	 * 分配推广员
	 * 
	 * @param request
	 * @param response
	 * @param redenvelope
	 * @param model
	 */
	@RequestMapping("relChannelUser")
	public String releaseRedenvelope(HttpServletRequest request,
			HttpServletResponse response, Model model){
		HashMap<String, Object> params = this.getParametersO(request);
		// 更新的页面跳转
		ChannelInfo channelInfo = channelInfoService.findOneChannelInfo(params);
		model.addAttribute("grant", true);
		model.addAttribute("channelInfo", channelInfo);
	
		return "userInfo/relChannelUser";
	}

	/**
	 * 弹出层，所有前台用户
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getAllFrontUser")
	public String getAllFrontUser(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Map<String, Object> param = this.getParametersO(request);
		try {
			
			param.put("queryType", "msg");
			List<String> allFrontUser = channelInfoService.findAllChUser(param);
			String outGroupHtml = "<ul class='tree treeFolder treeCheck expand'>"+StringUtils.join(allFrontUser.toArray(), "")+"</ul>";
			param.put("right_id", param.get("right_id"));
			param.put("userId", param.get("supportID"));
			param.put("type", param.get("type"));
			param.put("outGroupHtml", outGroupHtml);
			param.put("code", 1);
		} catch (Exception e) {
			e.printStackTrace();
			param.put("code", 0);
			param.put("message", "数据操作出现异常，请稍后再试！");
		}
		String queryParam = request.getQueryString();
		if (StringUtils.isNotBlank(queryParam)) {
			model.addAttribute("queryParam", queryParam);
		}
		this.setParameters(param, request);
		return "userInfo/allFrontUser";

	}
	
	/**
	 * 添加或修改推广员
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("saveUpdateChannelUserInfo")
	public String saveUpdateChannelUserInfo(HttpServletRequest request,
			HttpServletResponse response, Model model, User user) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (params.containsKey("id")) {
					ChannelInfo channelInfo = channelInfoService.findOneChannelInfo(params);
					// 更新的页面跳转
//					channelInfo = channelInfoService.findOneChannelInfo(params);
//					model.addAttribute("channelInfo", channelInfo);
					model.addAttribute("channelInfo", channelInfo);
				}
				url = "userInfo/saveChannelUser";
			} else {
				// 更新或者添加操作
				if (user.getId() != null) {
					
				} else {
					if(params.containsKey("channelId")){
						User validPhoneUser = null;
						User validIDCardUser = null;
						Map<String, Object> queryMap = new HashMap<String, Object>();
						// 手机号重复
						queryMap.put("id", user.getId());
						queryMap.put("userPhone", user.getUserPhone());
						validPhoneUser = userService.searchByUphoneAndUid(queryMap);
						// 证件号重复
//						queryMap.clear();
//						queryMap.put("id", user.getId());
//						queryMap.put("idNumber", user.getIdNumber());
//						validIDCardUser = userService.searchByUphoneAndUid(queryMap);
						
						if (validPhoneUser != null) {
							SpringUtils.renderDwzResult(response, false, "操作失败，该手机号已存在", DwzResult.CALLBACK_CLOSECURRENT,
									params.get("parentId").toString());
							return url;
						} 
//						else if (validIDCardUser != null) {
//							SpringUtils.renderDwzResult(response, false, "操作失败，该证件号已存在", DwzResult.CALLBACK_CLOSECURRENT,
//									params.get("parentId").toString());
//							return url;
//						} 
						else {
						
							HashMap<String, Object> map = new HashMap<String, Object>();
							String ip = this.getIpAddr(request);
							
							AESUtil aesEncrypt = new AESUtil();			
							String passWord = MD5coding.MD5(aesEncrypt.encrypt(ConfigConstant
									.getConstant(Constant.DEFAULT_PWD),""));//加密
							user.setUserFrom(params.get("channelId").toString());
							user.setCreateIp(ip);
							user.setPassword(passWord);
							user.setUserName(user.getUserPhone());
							user.setEquipmentNumber("");//设备号
							user.setAmountMax(String.valueOf(Constant.AMOUNT_MAX));
							user.setAmountAvailable(String.valueOf(Constant.AMOUNT_MAX));
							userService.saveUser(user);
							map.put("userPhone",user.getUserPhone());
							User findUser = userService.searchUserByCheckTel(map);
							if(findUser!=null){
								
								String inviteUserid =Base64Utils.encodeStr(findUser.getId());
								
								Map<String, String> keys = SysCacheUtils
										.getConfigParams(BackConfigParams.APP_IMG_URL);
								String appurl = keys.get("APP_IMG_URL");
								String qrurl= appurl+request.getContextPath()+
										"/"+"act/light-loan-xjx?invite_code="+inviteUserid+"&user_from="+user.getUserFrom();
								
								String qrName = MD5coding.MD5(String.valueOf(user.getId())) + ".jpg";// 二维码图片名称
								String savePath="/" + PropertiesUtil.get("FILEPATH","D:/") + "/" + Constant.QR_FILEPATH + "/" + qrName;
								String qrfileRealPath = request.getSession().getServletContext().getRealPath("/" + PropertiesUtil.get("FILEPATH","D:/") + "/" + Constant.QR_FILEPATH + "/" + qrName); // 二维码本地存储路径
								
								String logoPathDir = request.getSession().getServletContext().getRealPath("common/web/images/logo_qr_xjx.png"); // LOGO获取本地存储路径
								
								QrCodeUtil.encode(qrurl, 300, 300, logoPathDir, qrfileRealPath);
								
								params.put("userId",findUser.getId());
								params.put("channelId",params.get("channelId"));
								params.put("relPath",savePath.replaceAll("\\\\", "\\/"));
								params.put("remark",qrurl);
								
								channelInfoService.insertChannelUserInfo(params);
							}else{
								SpringUtils.renderDwzResult(response, false, "添加用户失败",
										DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
												.toString());
							}
						}
					}else{
						SpringUtils.renderDwzResult(response, false, "添加失败", DwzResult.CALLBACK_CLOSECURRENT,
								params.get("right_id").toString());
						return url;
					}
					//channelInfoService.updateById(channelInfo);
				}
				SpringUtils.renderDwzResult(response, true, "操作成功",
						DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId")
								.toString());
			}
		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				SpringUtils.renderDwzResult(response, false, "操作失败,原因："
						+ erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get(
						"parentId").toString());
			}
			logger.error("添加渠道信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}

	/**
	 * 删除角色
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("deleteChannelInfo")
	public void deleteChannelInfo(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		try {
			Integer id = Integer.parseInt(params.get("id").toString());
			channelInfoService.deleteChannelInfoById(id);
			flag = true;
		} catch (Exception e) {
			logger.error("deleteRole error", e);
		}
		SpringUtils.renderDwzResult(response, flag, flag ? "删除用户成功" : "删除用户失败",
				DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
						.toString());
	}
	/**
	 * 推广统计(渠道)
	 * 
	 * @param request
	 * @param response
	 * @param redenvelope
	 * @param model
	 */
	
	@RequestMapping("getChannelReportPage")
	public String getChannelReportPage(HttpServletRequest request,HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			HashMap<String, Object> chMap = new HashMap<String,Object>();
			BackUser backUser=this.loginAdminUser(request);
			if(backUser!=null&&!StringUtils.isBlank(backUser.getUserAddress())){
				HashMap<String, Object> pm = new HashMap<String,Object>();
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo= channelInfoService.findOneChannelInfo(pm);
				if(channelInfo!=null){
					params.put("channelCode", channelInfo.getChannelCode());
					chMap.put("channelCode", channelInfo.getChannelCode());
				}
			}
			//params.put("noAdmin", Constant.ADMINISTRATOR_ID);
			PageConfig<ChannelReport> pageConfig = channelReportService.findPage(params);
			
			List<ChannelInfo> channelList = channelInfoService.findAll(chMap);
			model.addAttribute("channelList", channelList);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getChannelReportPage error", e);
		}
		return "userInfo/channelReportPage";
	}
	
	/**
	 * 推广统计(地区)
	 * 
	 * @param request
	 * @param response
	 * @param redenvelope
	 * @param model
	 */
	
	@RequestMapping("getChannelPrReportPage")
	public String getChannelPrReportPage(HttpServletRequest request,HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			HashMap<String, Object> chMap = new HashMap<String,Object>();
			BackUser backUser=this.loginAdminUser(request);
			if(backUser!=null&&!StringUtils.isBlank(backUser.getUserAddress())){
				HashMap<String, Object> pm = new HashMap<String,Object>();
				pm.put("channelCode", backUser.getUserAddress());
				ChannelInfo channelInfo= channelInfoService.findOneChannelInfo(pm);
				if(channelInfo!=null){
					params.put("channelCode", channelInfo.getChannelCode());
					chMap.put("channelCode", channelInfo.getChannelCode());
				}
			}
			//params.put("noAdmin", Constant.ADMINISTRATOR_ID);
			PageConfig<ChannelReport> pageConfig = channelReportService.findPrPage(params);
			
			List<ChannelInfo> channelList = channelInfoService.findAll(chMap);
			model.addAttribute("channelList", channelList);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getChannelReportPage error", e);
		}
		return "userInfo/channelPrReportPage";
	}
	
	
	/**
	 * 推广统计excel
	 */
	@RequestMapping( "channelReportToExcel")
	public void borrowChartExcel(HttpServletResponse response,
			HttpServletRequest request, Model model) {
		Map<String, Object> params = getParametersO(request);
		try {
			List<ChannelReport> channelReport = channelReportService.getAllChannelReports(params);
			String[] titles = { "渠道商", "日期", "注册量", "实名人数", "绑卡人数", "紧急联系人人数", "运营商认证", "支付宝人数", "芝麻人数",
					"工作信息人数", "申请借款人数", "借款成功人数", "通过率", "放款总金额"};
			List<Object[]> contents = new ArrayList<Object[]>();
			for (ChannelReport reports : channelReport) {
				String[] conList = new String[titles.length];
				conList[0] = reports.getChannelName().toString();
				conList[1] = DateUtil.getDateFormat(reports.getReportDate(), "yyyy-MM-dd");
				conList[2] = reports.getRegisterCount().toString();
				conList[3] = reports.getAttestationRealnameCount().toString();
				conList[4] = reports.getAttestationBankCount().toString();
				conList[5] = reports.getContactCount().toString();
				conList[6] = reports.getJxlCount().toString();
				conList[7] = reports.getAlipayCount().toString();
				conList[8] = reports.getZhimaCount().toString();
				conList[9] = reports.getCompanyCount().toString();
				conList[10] = reports.getBorrowApplyCount().toString();
				conList[11] = reports.getBorrowSucCount().toString();
				conList[12] = reports.getPassRate().toString();
				conList[13] = (reports.getIntoMoney().divide(new BigDecimal(100))).toString();
				contents.add(conList);
			}
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(("report-data" + ".xls").getBytes("UTF-8"),
							"ISO8859-1"));
			response.setContentType("application/msexcel");// 定义输出类型
			 SXSSFWorkbook wb = new SXSSFWorkbook(10000);
			ExcelUtil.buildExcel(wb, "渠道商统计报表", titles, contents, 0, 0, os);
			//ExcelUtil.buildExcel(os, "借款统计趋势图报表", titles, contents);
		} catch (Exception e) {
			logger.error("导出excel失败", e);
			e.printStackTrace();
		}
	}
	
	/**
	 * 推广统计(地区)excel
	 */
	@RequestMapping( "channelPrReportToExcel")
	public void channelPrReportToExcel(HttpServletResponse response,
			HttpServletRequest request, Model model) {
		Map<String, Object> params = getParametersO(request);
		try {
			List<ChannelReport> channelReport = channelReportService.getAllPrChannelReports(params);
			String[] titles = { "省份","城市","区域","渠道商", "日期", "注册量", "实名人数", "绑卡人数", "紧急联系人人数", "运营商认证", "支付宝人数", "芝麻人数",
					"工作信息人数", "申请借款人数", "借款成功人数", "通过率", "放款总金额"};
			List<Object[]> contents = new ArrayList<Object[]>();
			for (ChannelReport reports : channelReport) {
				String[] conList = new String[titles.length];
				conList[0] = reports.getChannelProvince().toString();
				conList[1] = reports.getChannelCity().toString();
				conList[2] = reports.getChannelArea().toString();
				conList[3] = reports.getChannelName().toString();
				conList[4] = DateUtil.getDateFormat(reports.getReportDate(), "yyyy-MM-dd");
				conList[5] = reports.getRegisterCount().toString();
				conList[6] = reports.getAttestationRealnameCount().toString();
				conList[7] = reports.getAttestationBankCount().toString();
				conList[8] = reports.getContactCount().toString();
				conList[9] = reports.getJxlCount().toString();
				conList[10] = reports.getAlipayCount().toString();
				conList[11] = reports.getZhimaCount().toString();
				conList[12] = reports.getCompanyCount().toString();
				conList[13] = reports.getBorrowApplyCount().toString();
				conList[14] = reports.getBorrowSucCount().toString();
				conList[15] = reports.getPassRate().toString();
				conList[16] = (reports.getIntoMoney().divide(new BigDecimal(100))).toString();
				contents.add(conList);
			}
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(("report-data" + ".xls").getBytes("UTF-8"),
							"ISO8859-1"));
			response.setContentType("application/msexcel");// 定义输出类型
			 SXSSFWorkbook wb = new SXSSFWorkbook(10000);
			ExcelUtil.buildExcel(wb, "渠道商统计报表", titles, contents, 0, 0, os);
			//ExcelUtil.buildExcel(os, "借款统计趋势图报表", titles, contents);
		} catch (Exception e) {
			logger.error("导出excel失败", e);
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 生成二维码
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("deleteChannelInfo")
	public void qrChannel(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		try {
			Integer id = Integer.parseInt(params.get("id").toString());
			channelInfoService.deleteChannelInfoById(id);
			flag = true;
		} catch (Exception e) {
			logger.error("deleteRole error", e);
		}
		SpringUtils.renderDwzResult(response, flag, flag ? "删除用户成功" : "删除用户失败",
				DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
						.toString());
	}
	
	
	/**
	 * 封装map存入request中
	 * @param map
	 * @param request
	 */
	
	public void setParameters(Map map,HttpServletRequest request) {
		if (request == null) {
			request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		}
		if (map != null) {
			Iterator it = map.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = map.get(key);
				request.setAttribute(key, value);
			}
		}
	}
}
